package com.xg.realm;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    Map<String ,String > userMap= new HashMap<>(16);
    {

        //userMap.put("xg","123456");
        userMap.put("xg","f51703256a38e6bab3d9410a070c32ea");
        super.setName("customRealm");
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName= (String) principalCollection.getPrimaryPrincipal();
        //从数据库中或者缓存中获取角色
        Set<String> roles=getRolesByUserName(userName);
        Set<String> permissions=getPermissionsByUserName(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }

    private Set<String> getPermissionsByUserName(String userName) {
        Set<String> sets=new HashSet<>();
        sets.add("user:delete");
        sets.add("user:add");

    return sets;
    }

    private Set<String> getRolesByUserName(String userName){
        Set<String> sets=new HashSet<>();
        sets.add("admin");
        sets.add("user");
        return sets;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.从主体传过来的认证信息中，获得用户
        String userName= (String) authenticationToken.getPrincipal();
        //2.通过用户名到数据库中获取凭证
        String password =getPasswordByUserName(userName);

        if(StringUtils.isEmpty(password)){
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(userName,password,"customRealm");
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("salt"));
        return simpleAuthenticationInfo;
    }



    //模拟数据库
    private String getPasswordByUserName(String userName){

        return userMap.get(userName);
    }

    public static void main(String[] args) {
        Md5Hash md5Hash=new Md5Hash("123456","salt");
        System.out.println(md5Hash);
    }
}
